package com.jackrain.nea.wms.lts;


import com.alibaba.fastjson.JSONObject;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.wms.mq.SendMqService;
import com.jackrain.nea.wms.service.*;
import com.jackrain.nea.wms.utils.ObjectToUtil;
import com.jackrain.nea.wms.utils.RecLogUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class JobRunnerDispatcher implements JobRunner {

    public final static FastDateFormat DATE_FORMAT = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");

    private static Logger logger = LoggerFactory.getLogger(JobRunnerDispatcher.class.getName());

    private static final ConcurrentHashMap<String, JobRunner> JOB_RUNNER_MAP = new ConcurrentHashMap<String, JobRunner>();

    private static final String WMS_ORDER_IN = "wms_procurein_post";
    private static final String WMS_ORDER_OUT = "wms_procureout_post";
    private static final String WMS_TRAN_IN = "wms_tranin_post";
    private static final String WMS_TRAN_OUT = "wms_tranout_post";
    private static final String WMS_ORDER_CHANGE = "wms_tranchange_post";
    private static final String WMS_ORDER_UPDATE = "wms_tranupdate_post";
    private static final String DL_QUERY_DATA = "dl_mq_post";

    static {
//
//        JOB_RUNNER_MAP.put(WMS_ORDER_IN, new JobRunnWmsOrderIN());
//        JOB_RUNNER_MAP.put(WMS_ORDER_OUT, new JobRunnWmsOrderOut());
//        JOB_RUNNER_MAP.put(WMS_TRAN_IN, new JobRunnWmsTranIn());
//        JOB_RUNNER_MAP.put(WMS_TRAN_OUT, new JobRunnWmsTranOut());
//        JOB_RUNNER_MAP.put(WMS_ORDER_CHANGE, new JobRunnWmsTranChange());
//        JOB_RUNNER_MAP.put(WMS_ORDER_UPDATE, new JobRunnWmsTranUpdate());
        JOB_RUNNER_MAP.put(DL_QUERY_DATA, new JobRunnQueryDLDataPost());

    }

    @Override
    public Result run(JobContext jobContext) throws Throwable {
        String type = jobContext.getJob().getParam("type");
        if (!JOB_RUNNER_MAP.containsKey(type)) {
            return null;
        }
        return JOB_RUNNER_MAP.get(type).run(jobContext);
    }

    private static class JobRunnQueryDLDataPost implements JobRunner {


        @Override
        public Result run(JobContext jobContext) {

            String topic = jobContext.getJob().getParam("topic");
            String tag = jobContext.getJob().getParam("tag");
            //查询条数
            int pageSize = ObjectToUtil.getInt(jobContext.getJob().getParam("pageSize"), 0);
            //每条消息数据量
            int rowSize = ObjectToUtil.getInt(jobContext.getJob().getParam("rowSize"), 1);
//            long taskId = RecLogUtils.recCloudTaskLog("I", topic, tag);
            List<HashMap> listData = new ArrayList<>();

            try {
                if (pageSize <= 0) {
                    pageSize = 1;
                }
                String beanName = "com.jackrain.fc.service." + tag;
                BaseProcess baseProcess = (BaseProcess) ApplicationContextHandle.getBean(beanName);
                listData = baseProcess.queryData(pageSize);


                if (listData == null || listData.size() == 0) {
                    return new Result(Action.EXECUTE_SUCCESS, "发送失败，查询数据为空");
                }

                int row = rowSize;
                int page = listData.size() % row == 0 ? listData.size() / row : listData.size() / row + 1;
                for (int k = 0; k < page; k++) {
                    List<HashMap> rowArray = new ArrayList();
                    for (int j = 0; j < row; j++) {
                        int index = k * row + j;
                        if (index >= listData.size()) {
                            break;
                        }
                        rowArray.add(listData.get(index));
                    }
                    //发消息
                    SendMqService sendMqService = ApplicationContextHandle.getBean(SendMqService.class);
                    ValueHolder vh = new ValueHolder();
                    JSONObject dataObject = new JSONObject();
                    dataObject.put("list", rowArray);
                    dataObject.put("tag", tag);
//                    dataObject.put("taskId", taskId);
                    vh.put("pdesc", dataObject.toJSONString());
                    sendMqService.sendMqinfo(dataObject, topic, tag, vh);
                }

                log.debug("JobRunnDLRetailPost start online!");
                return new Result(Action.EXECUTE_SUCCESS, "发送成功" + "page" + page);
            } catch (Exception e) {

                String error = "";
                if ((e instanceof NDSException)) {
                    error = e.getMessage();
                } else {
                    StringWriter sw = new StringWriter();
                    PrintWriter pw = new PrintWriter(sw);
                    e.printStackTrace(pw);
                    error = sw.toString();
                }
                //记录日志
                logger.debug("Run job failed!" + error);
//                RecLogUtils.recCloudErrorLog(tag + "消息任务错误", error, topic);
//                RecLogUtils.updateCloudTaskLog(taskId, "Y", error);
                return new Result(Action.EXECUTE_FAILED, "rowSize" + rowSize + "listData" + listData.size() + "listData" + listData + "error" + error);
            }
        }
    }


    /**
     * 采购入库定时任务6
     */
//    private static class JobRunnWmsOrderIN implements JobRunner {
//        @Override
//        public Result run(JobContext jobContext) {
//
//            String topic = jobContext.getJob().getParam("topic");
//            String tag = jobContext.getJob().getParam("tag");
//            int pageSize = ObjectToUtil.getInt(jobContext.getJob().getParam("pageSize"), 0);
//
//            //记录日志
//            long taskId = RecLogUtils.recCloudTaskLog("I", topic, tag);
//            try {
//                //
//                WmsOrderInService viewVipUpService = ApplicationContextHandle.getBean(WmsOrderInService.class);
//                JSONObject retObject = viewVipUpService.exec(taskId, topic, tag,pageSize).toJSONObject();
//                BizLogger bizLogger = jobContext.getBizLogger();
//                log.debug("JobRunnVipUp start online!");
//                bizLogger.info(retObject.toJSONString());
//                logger.debug("retObject============>" + retObject.toJSONString());
//                logger.debug("-----------------------END-----------------------");
//                return new Result(Action.EXECUTE_SUCCESS, null);
//            } catch (Exception e) {
//
//                String error = "";
//                if ((e instanceof NDSException)) {
//                    error = e.getMessage();
//                } else {
//                    StringWriter sw = new StringWriter();
//                    PrintWriter pw = new PrintWriter(sw);
//                    e.printStackTrace(pw);
//                    error = sw.toString();
//                }
//                //记录日志
//                logger.debug("Run job failed!" + error);
//                RecLogUtils.recCloudErrorLog("采购入库任务错误", error, "");
//                RecLogUtils.updateCloudTaskLog(taskId, "Y", error);
//                return new Result(Action.EXECUTE_FAILED, e.getMessage());
//            }
//        }
//    }
    /**
     * 采购出库库定时任务
     */
//    private static class JobRunnWmsOrderOut implements JobRunner {
//        @Override
//        public Result run(JobContext jobContext) {
//
//            String topic = jobContext.getJob().getParam("topic");
//            String tag = jobContext.getJob().getParam("tag");
//            int pageSize = ObjectToUtil.getInt(jobContext.getJob().getParam("pageSize"), 0);
//
//            //记录日志
//            long taskId = RecLogUtils.recCloudTaskLog("I", topic, tag);
//            try {
//                //
//                WmsOrderOutService wmsOrderOutService = ApplicationContextHandle.getBean(WmsOrderOutService.class);
//                JSONObject retObject = wmsOrderOutService.exec(taskId, topic, tag,pageSize).toJSONObject();
//                BizLogger bizLogger = jobContext.getBizLogger();
//                log.debug("JobRunnVipUp start online!");
//                bizLogger.info(retObject.toJSONString());
//                logger.debug("retObject============>" + retObject.toJSONString());
//                logger.debug("-----------------------END-----------------------");
//                return new Result(Action.EXECUTE_SUCCESS, null);
//            } catch (Exception e) {
//
//                String error = "";
//                if ((e instanceof NDSException)) {
//                    error = e.getMessage();
//                } else {
//                    StringWriter sw = new StringWriter();
//                    PrintWriter pw = new PrintWriter(sw);
//                    e.printStackTrace(pw);
//                    error = sw.toString();
//                }
//                //记录日志
//                logger.debug("Run job failed!" + error);
//                RecLogUtils.recCloudErrorLog("采购出库任务错误", error, "");
//                RecLogUtils.updateCloudTaskLog(taskId, "Y", error);
//                return new Result(Action.EXECUTE_FAILED, e.getMessage());
//            }
//        }
//    }


    /**
     * 调拨入库定时任务
     */
//    private static class JobRunnWmsTranIn implements JobRunner {
//        @Override
//        public Result run(JobContext jobContext) {
//
//            String topic = jobContext.getJob().getParam("topic");
//            String tag = jobContext.getJob().getParam("tag");
//            int pageSize = ObjectToUtil.getInt(jobContext.getJob().getParam("pageSize"), 0);
//
//            //记录日志
//            long taskId = RecLogUtils.recCloudTaskLog("I", topic, tag);
//            try {
//                //
//                WmsTranInService wmsTranInService = ApplicationContextHandle.getBean(WmsTranInService.class);
//                JSONObject retObject = wmsTranInService.exec(taskId, topic, tag,pageSize).toJSONObject();
//                BizLogger bizLogger = jobContext.getBizLogger();
//                log.debug("JobRunnVipUp start online!");
//                bizLogger.info(retObject.toJSONString());
//                logger.debug("retObject============>" + retObject.toJSONString());
//                logger.debug("-----------------------END-----------------------");
//                return new Result(Action.EXECUTE_SUCCESS, null);
//            } catch (Exception e) {
//
//                String error = "";
//                if ((e instanceof NDSException)) {
//                    error = e.getMessage();
//                } else {
//                    StringWriter sw = new StringWriter();
//                    PrintWriter pw = new PrintWriter(sw);
//                    e.printStackTrace(pw);
//                    error = sw.toString();
//                }
//                //记录日志
//                logger.debug("Run job failed!" + error);
//                RecLogUtils.recCloudErrorLog("调拨入库任务错误", error, "");
//                RecLogUtils.updateCloudTaskLog(taskId, "Y", error);
//                return new Result(Action.EXECUTE_FAILED, e.getMessage());
//            }
//        }
//    }
//    /**
//     * 调拨出库定时任务
//     */
//    private static class JobRunnWmsTranOut implements JobRunner {
//        @Override
//        public Result run(JobContext jobContext) {
//
//            String topic = jobContext.getJob().getParam("topic");
//            String tag = jobContext.getJob().getParam("tag");
//            int pageSize = ObjectToUtil.getInt(jobContext.getJob().getParam("pageSize"), 0);
//
//            //记录日志
//            long taskId = RecLogUtils.recCloudTaskLog("I", topic, tag);
//            try {
//                //
//                WmsTranOutService wmsTranOutService = ApplicationContextHandle.getBean(WmsTranOutService.class);
//                JSONObject retObject = wmsTranOutService.exec(taskId, topic, tag,pageSize).toJSONObject();
//                BizLogger bizLogger = jobContext.getBizLogger();
//                log.debug("JobRunnVipUp start online!");
//                bizLogger.info(retObject.toJSONString());
//                logger.debug("retObject============>" + retObject.toJSONString());
//                logger.debug("-----------------------END-----------------------");
//                return new Result(Action.EXECUTE_SUCCESS, null);
//            } catch (Exception e) {
//
//                String error = "";
//                if ((e instanceof NDSException)) {
//                    error = e.getMessage();
//                } else {
//                    StringWriter sw = new StringWriter();
//                    PrintWriter pw = new PrintWriter(sw);
//                    e.printStackTrace(pw);
//                    error = sw.toString();
//                }
//                //记录日志
//                logger.debug("Run job failed!" + error);
//                RecLogUtils.recCloudErrorLog("调拨出库任务错误", error, "");
//                RecLogUtils.updateCloudTaskLog(taskId, "Y", error);
//                return new Result(Action.EXECUTE_FAILED, e.getMessage());
//            }
//        }
//    }
    /**
     * 库存转移定时任务
     */
//    private static class JobRunnWmsTranChange implements JobRunner {
//        @Override
//        public Result run(JobContext jobContext) {
//
//            String topic = jobContext.getJob().getParam("topic");
//            String tag = jobContext.getJob().getParam("tag");
//            int pageSize = ObjectToUtil.getInt(jobContext.getJob().getParam("pageSize"), 0);
//
//            //记录日志
//            long taskId = RecLogUtils.recCloudTaskLog("I", topic, tag);
//            try {
//                //
//                WmsTranChangeService wmsTranChangeService = ApplicationContextHandle.getBean(WmsTranChangeService.class);
//                JSONObject retObject = wmsTranChangeService.exec(taskId, topic, tag,pageSize).toJSONObject();
//                BizLogger bizLogger = jobContext.getBizLogger();
//                log.debug("JobRunnVipUp start online!");
//                bizLogger.info(retObject.toJSONString());
//                logger.debug("retObject============>" + retObject.toJSONString());
//                logger.debug("-----------------------END-----------------------");
//                return new Result(Action.EXECUTE_SUCCESS, null);
//            } catch (Exception e) {
//
//                String error = "";
//                if ((e instanceof NDSException)) {
//                    error = e.getMessage();
//                } else {
//                    StringWriter sw = new StringWriter();
//                    PrintWriter pw = new PrintWriter(sw);
//                    e.printStackTrace(pw);
//                    error = sw.toString();
//                }
//                //记录日志
//                logger.debug("Run job failed!" + error);
//                RecLogUtils.recCloudErrorLog("库存转移任务错误", error, "");
//                RecLogUtils.updateCloudTaskLog(taskId, "Y", error);
//                return new Result(Action.EXECUTE_FAILED, e.getMessage());
//            }
//        }
//    }
//    /**
//     * 库存调整定时任务
//     */
//    private static class JobRunnWmsTranUpdate implements JobRunner {
//        @Override
//        public Result run(JobContext jobContext) {
//
//            String topic = jobContext.getJob().getParam("topic");
//            String tag = jobContext.getJob().getParam("tag");
//            int pageSize = ObjectToUtil.getInt(jobContext.getJob().getParam("pageSize"), 0);
//
//            //记录日志
//            long taskId = RecLogUtils.recCloudTaskLog("I", topic, tag);
//            try {
//                //
//                WmsTranUpdateService wmsTranUpdateService = ApplicationContextHandle.getBean(WmsTranUpdateService.class);
//                JSONObject retObject = wmsTranUpdateService.exec(taskId, topic, tag,pageSize).toJSONObject();
//                BizLogger bizLogger = jobContext.getBizLogger();
//                log.debug("JobRunnVipUp start online!");
//                bizLogger.info(retObject.toJSONString());
//                logger.debug("retObject============>" + retObject.toJSONString());
//                logger.debug("-----------------------END-----------------------");
//                return new Result(Action.EXECUTE_SUCCESS, null);
//            } catch (Exception e) {
//
//                String error = "";
//                if ((e instanceof NDSException)) {
//                    error = e.getMessage();
//                } else {
//                    StringWriter sw = new StringWriter();
//                    PrintWriter pw = new PrintWriter(sw);
//                    e.printStackTrace(pw);
//                    error = sw.toString();
//                }
//                //记录日志
//                logger.debug("Run job failed!" + error);
//                RecLogUtils.recCloudErrorLog("库存调整任务错误", error, "");
//                RecLogUtils.updateCloudTaskLog(taskId, "Y", error);
//                return new Result(Action.EXECUTE_FAILED, e.getMessage());
//            }
//        }
//    }
}